<template>
  <main-content title="商城优惠券管理">
    <template #tab-bar>
      <el-radio-group
        v-model="searchForm.onlineStatus"
      >
        <el-radio-button
          v-for="item in onlineStatusList"
          :key="item.value"
          :label="item.value"
        >
          {{ item.label }}
        </el-radio-button>
      </el-radio-group>
    </template>

    <template #search-bar>
      <SearchBar inline>
        <template #normal>
          <el-form-item label="优惠券名称">
            <el-input
              v-model="searchForm.couponName"
              clearable
              placeholder="请输入优惠券名称"
            />
          </el-form-item>
          <el-form-item label="优惠券ID">
            <el-input
              v-model="searchForm.couponId"
              clearable
              placeholder="请输入优惠券ID"
            />
          </el-form-item>
          <el-form-item label="优惠券类型">
            <el-select
              v-model="searchForm.couponType"
              placeholder="请选择优惠券类型"
              clearable
            >
              <el-option
                v-for="item in CouponType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </template>
        <template #toolbar>
          <el-form-item>
            <el-button
              type="primary"
              @click="research"
            >
              查询
            </el-button>
            <el-button
              v-has="['080701']"
              type="primary"
              icon="Plus"
              @click="createCoupon"
            >
              新增优惠券
            </el-button>
          </el-form-item>
        </template>
      </SearchBar>
    </template>

    
    <LayoutTable
      ref="tableRef"
      url="mall/admin/product/getPageCouponInfo"
      :param="searchForm"
    >
      <el-table-column
        label="优惠券ID"
        width="180"
        prop="id"
      />
      <el-table-column
        label="优惠券名称"
        min-width="200"
        prop="name"
      />
      <el-table-column
        v-has="['080704']"
        label="优惠券状态"
        width="100"
      >
        <template #default="props">
          <el-switch
            v-model="props.row.onlineStatus"
            inline-prompt
            style="--el-switch-on-color: var(--el-color-primary);"
            active-text="启用"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
            :before-change="() => handleStatusChange(props.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="优惠券类型"
        width="100"
      >
        <template #default="props">
          {{ getCouponTypeName(props.row.couponType) }}
        </template>
      </el-table-column>
      <el-table-column
        label="售价"
        width="210"
      >
        <template #default="{row}">
          <!-- {{ getPointsAndMoneyString(row) }} -->
          {{ row.priceRange }}
        </template>
      </el-table-column>
      <el-table-column
        label="优惠券数量/领取量/使用量"
        width="210"
      >
        <template #default="{row}">
          {{ row?.totalStock ?? '0' }} / {{ row?.receiveCouponNum ?? '0' }} / {{ row?.usedCouponNum ?? '0' }}
        </template>
      </el-table-column>
      <el-table-column
        label="使用率"
        width="140"
        prop="usedRate"
      >
        <template #default="{row}">
          {{ (row?.usedRate ?? 0) + '%' }}
        </template>
      </el-table-column>

      <el-table-column
        label="更新时间"
        width="180"
      >
        <template #default="{row}">
          {{ formatTime(row.updateTime) }}
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        fixed="right"
        width="180"
      >
        <template #default="props">
          <el-button
            v-has="['080702']"
            type="primary"
            link
            @click="toEdit(props.row)"
          >
            编辑
          </el-button>

          <el-button
            v-has="['080703']"
            type="primary"
            link
            @click="editVipPrice(props.row)"
          >
            配置会员价
          </el-button>

          <el-button
            v-has="['080705']"
            type="danger"
            link
            @click="deleteCoupon(props.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </LayoutTable>
  </main-content>

  <!-- 新增-选择商品 -->
  <coupon-selector
    v-model:show="isShowCouponSelector"
    url="mall/admin/product/getOriginalCouponInfo"
    :search-form="{
      mallId: mallConfig.id
    }"
    @confirm="toCreate"
  />

  <!-- 配置会员价格 -->
  <coupon-vip-price-config
    v-model:show="isShowVipPriceConfig"
    :row="currentRow"
    @finished="research"
  />

  <!-- 修改优惠券批次库存 -->
  <edit-coupon-batch-stock
    v-model:show="isShowEditStock"
    :row="currentRow"
    @confirm="editStockConfirm"
  />
</template>

<script setup lang="ts">
import type { ICouponSelectorRow } from "@/api/modules/marketingTool"
import type { ICouponManageRow } from "@/api/modules/pointsMall"
import moment from "moment";
import { useCouponType } from "@/views/marketingTool/compositions/useCouponType"
// import { getPointsAndMoneyString } from "@/utils/index"
import { switchGoodsStatus, deleteGoods } from "@/api/pointsMall"
import CouponSelector from "@/views/marketingTool/components/CouponSelector.vue"
import CouponVipPriceConfig from "@/views/pointsMall/components/CouponVipPriceConfig.vue";
import EditCouponBatchStock from "@/views/pointsMall/components/EditCouponBatchStock.vue";
import { useMallConfig } from "@/views/pointsMall/compositions/useMallConfig";

const router = useRouter()
const { getCouponTypeName, CouponType } = useCouponType()
const { mallConfig } = useMallConfig()

const searchForm = reactive({
  mallId: mallConfig.value.id,
  onlineStatus: null,
  couponName: "",
  couponId: "",
  couponType: "",
})
const tableRef = ref();
const research = () => {
  tableRef.value.research();
}
const currentRow = ref();

const onlineStatusList = ref([ {
  label: '全部',
  value: null,
}, {
  label: '启用',
  value: 1,
}, {
  label: '禁用',
  value: 0,
} ])

// 优惠券状态切换
const handleStatusChange: (row: ICouponManageRow) => Promise<boolean> = (row) => {
  return new Promise<boolean>((resolve) => {
    if (row.onlineStatus) {
      ElMessageBox.confirm(
        "禁用优惠券，批次库存将全部归还，是否确认禁用？",
        "提示"
      ).then(async () => {
        const rs = await switchGoodsStatus({
          id: row.id,
          onlineStatus: 0,
        });
        if (rs.code === 200) {
          resolve(true)
          research()
        }
      })
    } else {
      currentRow.value = row
      resolve(false)
      isShowEditStock.value = true
    }
  }).catch(e => {
    console.log(e)
    return Promise.resolve(false)
  })
}

const isShowEditStock = ref(false)
const editStockConfirm = () => {
  research()
}


const formatTime = (timestamp: number) => {
  return timestamp ? moment(timestamp).format("YYYY.MM.DD HH:mm:ss") : ''
}

// 编辑
const toEdit = (row: ICouponManageRow) => {
  console.log("编辑！！！")
  router.push({
    path: "/mall/couponManage/edit",
    query: {
      id: row.id
    }
  })
}

// 新增选择器
const isShowCouponSelector = ref(false)
const createCoupon = () => {
  isShowCouponSelector.value = true
}

// 新增
const toCreate = (row: ICouponSelectorRow) => {
  console.log("新增！！！")
  router.push({
    path: "/mall/couponManage/create",
    query: {
      couponDefineId: row.id
    }
  })
}

// 删除
const deleteCoupon = (row: ICouponManageRow) => {
  ElMessageBox.confirm("确认删除？", "提示").then(async () => {
    const rs = await deleteGoods({ id: row.id })
    if (rs.code === 200) {
      ElMessage.success("删除成功")
      research()
    }
  }).catch(() => {
    void 0
  })
}

// 配置会员价
const isShowVipPriceConfig = ref(false)
const editVipPrice = (row: ICouponManageRow) => {
  isShowVipPriceConfig.value = true
  currentRow.value = row
}


</script>

<style scoped lang="scss">

</style>